package org.example.bombermanserver;

import org.example.bombermanserver.handler.JsonMessageDecoder;
import org.example.bombermanserver.handler.JsonMessageEncoder;
import org.example.bombermanserver.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;

public class BombermanServer {

    public static void start(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();

                            // 必须先加行分隔解码器，保证客户端发送的一行 JSON 是一个完整包
                            p.addLast(new LineBasedFrameDecoder(1024));

                            // 再加 JSON 编解码
                            p.addLast(new JsonMessageDecoder());
                            p.addLast(new JsonMessageEncoder());

                            // 业务处理器
                            p.addLast(new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            System.out.println("Netty server started on port: " + port);

            // 阻塞直到服务端关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    //也可直接运行
    public static void main(String[] args) {
        start(9000);
    }
}
